// 升级类
var upgrade = Vue.component('build-upgrade', {
    template: readComponentHTML("upgrade"),
    data() {
        return {
            ruleForm: {
                configs: [],
                path: '',
                type: "PostTask",
                module: '',
                tableName: '',
                tableData: [{
                    field: '',
                    type: '',
                    isnull: false,
                    prikey: false
                }],
                extendJson: '{}'
            },
            versionList: [],
            modulesList: [],
            haveFile: true,
            isLocation: true,
            haveModule: false,
            buildTable: false,
            buildEntity: false,
            rules: {
                path: [
                    {required: true, message: '请输入项目路径', trigger: 'blur'}
                ],
                tableName: [
                    {required: true, message: '请输入表名', trigger: 'blur'}
                ],
                module: [
                    {required: true, message: '请选择Module', trigger: 'change'}
                ],
            },
            fileList: [],
        };
    },
    mounted() {
        this.ruleForm.path = this.$store.state.projectPath;
        this.initModules();
        this.ruleForm.configs = ["location"];
        this.getExtendJson.apply(this, ["upgrade", "defaultExtend.json"]);
    },
    methods: {
        addTooltip(h, {column, $index}) {
            return [
                column.label,
                h(
                    'el-tooltip',
                    {
                        props: {
                            content: '在输入框回车、双击[新建]Delete[删除]', // 鼠标悬停时要展示的文字提示
                            placement: 'top' // 悬停内容展示的位置
                        }
                    },
                    [h('span', {class: {'el-icon-question': true}})] // 图标
                )
            ]
        },
        changebuildEntity(e) {
            this.buildEntity = e;
        },
        changebuildTable(e) {
            this.buildTable = e;
            this.buildEntity = e;
            if (e) {
                this.ruleForm.configs.push("buildTable");
                this.ruleForm.configs.push("buildTableEntity");
                this.ruleForm.configs.push("buildTableEntityDAO");
            }
        },
        fieldKeyUp(index, event) {
            switch (event.keyCode) {
                case 13:
                    this.addNewRow(index);
                    break;
                case 46:
                    this.delRow(index);
                    break;
            }
        },
        delRow(index) {
            if (this.ruleForm.tableData.length == 1) {
                this.$message({
                    message: '请至少保留一行数据',
                    type: 'warning'
                })
                return;
            }
            this.ruleForm.tableData.splice(index, 1);
        },
        addNewRow(index) {
            var lastIndex = null;
            if (index.target) {
                lastIndex = this.ruleForm.tableData.length - 1;
            } else if ((index + 1) == this.ruleForm.tableData.length) {
                lastIndex = index;
            }
            if (lastIndex != null) {
                if (this.ruleForm.tableData[lastIndex].field) {
                    this.ruleForm.tableData.push({
                        field: '',
                        type: '',
                        isnull: false,
                        prikey: false
                    })
                } else {
                    this.$message({
                        message: '上一行字段名不为空才可以新增一行',
                        type: 'warning'
                    })
                }
            }
        },
        // 获取当前配置的扩展包路径下升级类版本列表集合
        initProject() {
            var that = this;
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    that.initModules();
                }
            })
        },
        initModules() {
            if (this.ruleForm.path) {
                var that = this;
                that.openLoading();
                var postData = new URLSearchParams()
                postData.append("path", this.ruleForm.path)
                axios.post(
                    "/simpledevelop/upgrade/getModules",
                    postData
                ).then(response => {
                    if (response.data.reasonCode == 2000) {
                        that.haveModule = true;
                        that.modulesList = response.data.data;
                        that.ruleForm.module = that.modulesList[0];
                        that.init();
                    } else {
                        that.haveModule = false;
                        this.$message.error(response.data.desc);
                    }
                    that.closeLoading();
                })
                    .catch(error => this.$message.error(JSON.stringify(error)))
            }
        },
        // 初始化升级类版本列表集合
        init() {
            if (this.ruleForm.path && this.ruleForm.module) {
                var that = this;
                that.openLoading();
                var postData = new URLSearchParams()
                postData.append("type", this.ruleForm.type);
                postData.append("path", this.ruleForm.path);
                postData.append("module", this.ruleForm.module);
                axios.post(
                    "/simpledevelop/upgrade/getVersions",
                    postData
                ).then(function (response) {
                    that.versionList = response.data
                    that.closeLoading();
                }).catch(error => this.$message.error(JSON.stringify(error)))
            } else {
                this.versionList = [];
            }
        },
        // 上传文件 构建资源升级类 或直接构建升级类
        submitUpload() {
            var that = this;
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    if (!that.buildTable) {
                        // 文件上传
                        that.openLoading();
                        let uploadForm = new FormData()
                        uploadForm.append("type", this.ruleForm.type);
                        uploadForm.append("path", this.ruleForm.path);
                        uploadForm.append("configs", this.ruleForm.configs);
                        uploadForm.append("module", this.ruleForm.module);
                        uploadForm.append("extendJson", this.ruleForm.extendJson);
                        if (this.haveFile && this.$refs.upload.uploadFiles.length != 0) {
                            for (let i = 0; i < this.$refs.upload.uploadFiles.length; i++) {
                                uploadForm.append("file", this.$refs.upload.uploadFiles[i].raw);
                            }
                        }
                        axios.post(
                            "/simpledevelop/upgrade/upgrade",
                            uploadForm, {
                                headers: {
                                    'Content-Type': 'multipart/form-data;charset=UTF-8',
                                    "Accept": "*/*"
                                }
                            }
                        ).then(function (response) {
                            if (response.data.reasonCode == 2000) {
                                that.$alert(response.data.desc, '操作结果', {
                                    dangerouslyUseHTMLString: true
                                })
                                that.init();
                            } else {
                                that.$message.error(response.data.desc);
                            }
                            if (that.haveFile) {
                                that.$refs.upload.clearFiles();
                            }
                            that.closeLoading();
                        }).catch(error => this.$message.error(JSON.stringify(error)));
                    } else {
                        var havaPriKey = false;
                        for (var i in this.ruleForm.tableData) {
                            var data = this.ruleForm.tableData[i];
                            if (!data.field) {
                                that.$message.error("不允许有字段为空");
                                return;
                            }
                            if (!data.type) {
                                that.$message.error("字段:" + data.field + "请选择字段类型");
                                return;
                            }
                            if (data.prikey) {
                                havaPriKey = true;
                            }
                        }
                        if (!havaPriKey) {
                            that.$message.error("请至少选择一个主键");
                            return;
                        }
                        axios.post(
                            "/simpledevelop/upgrade/upgrade/table",
                            JSON.stringify(this.ruleForm), {
                                headers: {
                                    'Content-Type': 'application/json'
                                }
                            }
                        ).then(function (response) {
                            that.closeLoading();
                            if (response.data.reasonCode == 2000) {
                                that.$alert(response.data.desc, '操作结果', {
                                    dangerouslyUseHTMLString: true
                                })
                                that.init();
                            } else {
                                that.$message.error(response.data.desc);
                            }
                        }).catch(error => this.$message.error(JSON.stringify(error)));
                    }
                } else {
                    this.$message.error('请完善必填信息');
                }
            })
        },
        // 点击本地模式 展示和隐藏checkbox和项目路径的input输入框
        changeisLocation: function (e) {
            this.isLocation = e;
            if (this.ruleForm.type === "PostTask") {
                this.haveFile = e;
            }
            if (!e) {
                this.haveModule = false;
            }
            // 勾选本地模式后 如果有路径重新初始化module
            if (e && this.ruleForm.path) {
                this.initModules();
            }
        },
        // 改变构建类型 给出一些初始值
        changeType: function (type) {
            switch (type) {
                case "PostTask":
                    this.haveFile = true;
                    this.buildTable = false;
                    break;
                case "UpgradeTask":
                    this.haveFile = false;
                    this.buildTable = false;
                    this.ruleForm.configs = ["location"];
                    break;
            }
            if (this.haveModule) {
                this.init();
            }
        },
        test: function (index, type) {
            if (type === 'pri') {
                this.ruleForm.tableData[index].isnull = true;
            }
            if (type === 'notNull' && this.ruleForm.tableData[index].prikey && !this.ruleForm.tableData[index].isnull) {
                this.$message({
                    message: '主键必须为非空',
                    type: 'warning'
                })
                this.ruleForm.tableData[index].isnull = true;
            }
        }
    },
    computed: {
        listenExtPath() {
            return this.$store.state.projectPath;
        },
        listenProjectPath() {
            return this.ruleForm.path;
        },
        listenHaveModule() {
            return this.haveModule;
        }
    },
    watch: {
        listenExtPath: function (newValue, oldValue) {
            this.ruleForm.path = newValue;
            this.initModules();
        },
        listenProjectPath: function (newValue, oldValue) {
            if (!newValue) {
                this.haveModule = false;
                return;
            }
        },
        listenHaveModule: function (newValue, oldValue) {
            if (!newValue) {
                this.versionList = [];
                this.modulesList = [];
            }
        },
    }
})